package com.jinxin.phonecloudmusic.myapplication.fragment.fra;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;

import com.jinxin.phonecloudmusic.myapplication.R;
import com.jinxin.phonecloudmusic.myapplication.adapter.MusicSearchAdapter;
import com.jinxin.phonecloudmusic.myapplication.app.JxscApp;
import com.jinxin.phonecloudmusic.myapplication.base.BaseFragment;
import com.jinxin.phonecloudmusic.myapplication.db.SPM;
import com.jinxin.phonecloudmusic.myapplication.event.MusicControlEvent;
import com.jinxin.phonecloudmusic.myapplication.utils.RxBus;
import com.jinxin.phonecloudmusic.myapplication.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;

/**
 * Created by ZJ on 2017/10/26 0026.
 * 搜索历史碎片
 */

public class MusicSearchHistoryFragment extends BaseFragment{
    @BindView(R.id.lv_history_search)
    ListView lvHistorySearch;
    @BindView(R.id.img_search_historty)
    ImageView imgSearchHistory;
    @BindView(R.id.et_info_text)
    EditText etInfoText;
    @BindView(R.id.btn_delete_all)
    Button btnDeleteAll;
    @BindView(R.id.iv_back)
    ImageView ivBack;

    private String b;
    private List<String> stringList = new ArrayList<>();
    private List<String> stringHistoryData=new ArrayList<>();
    private String itemStr;
    private List<String> currentData = new ArrayList<>();

    private MusicSearchAdapter musicSearchAdapter;

    @Override
    public View inflate(LayoutInflater inflater, ViewGroup container) {
        return inflater.inflate(R.layout.fra_music_search_history, container, false);
    }

    @Override
    public void initData() {
        saveHistory();
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RxBus.getDefault().post(new MusicControlEvent(1002,"",""));//关闭当前碎片
            }
        });
    }

    //保存历史记录
    private void saveHistory(){
        RxBus.getDefault().register(MusicControlEvent.class).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<MusicControlEvent>() {
            @Override
            public void accept(MusicControlEvent event) throws Exception {
                if ((event.getTag()) == 100) {//0:播放包括上下首
                    itemStr= (String)musicSearchAdapter.getItem((int) event.getObj1());
                    if (itemStr!=null&&musicSearchAdapter!=null) {//判空处理
                        musicSearchAdapter.remove(itemStr);
                        //SPM.saveListStr1("历史搜索", "historySearch", stringHistoryData,itemStr);
                    }
                }
            }
        });
        btnDeleteAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //移除配置表
                SPM.removeSP("历史搜索");
                if (musicSearchAdapter!=null) {
                    musicSearchAdapter.removeAll();
                }else {
                    ToastUtil.showShort(JxscApp.getContext(),"暂无历史记录");
                }
                stringHistoryData = null;
                //强制清空
                SPM.saveListStr("历史搜索", "historySearch", null,null);
                List<String> q=SPM.getListStr("历史搜索", "historySearch", "");
            }
        });
        imgSearchHistory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                JxscApp.searchBack=true;
                //存历史记录（保留搜索前6个）
                if (!TextUtils.isEmpty(etInfoText.getText().toString())) {
                    b = etInfoText.getText().toString();
                    //存历史记录string，得到历史记录的前6个取为一个list

                    //先清空再添加
                    stringList.clear();
                    if (!SPM.getListStr("历史搜索", "historySearch", "").contains(b)) {

                        stringList.add(b);
                        SPM.saveListStr("历史搜索", "historySearch", stringList);
                    }
                    currentData.clear();
                    List<String> a = SPM.getListStr("历史搜索", "historySearch", "");
                    if (SPM.getListStr("历史搜索", "historySearch", "").size() > 6) {
                        for (int i = 0; i < 6; i++) {
                            currentData.add(SPM.getListStr("历史搜索", "historySearch", "").get(i));
                        }
                    } else {
                        for (int i = 0; i < SPM.getListStr("历史搜索", "historySearch", "").size(); i++)
                            currentData.add(SPM.getListStr("历史搜索", "historySearch", "").get(i));
                    }
                } else {
                    ToastUtil.showShort(JxscApp.getContext(), "搜索内容不能为空！");
                    return;
                }
                //handler.obtainMessage(1).sendToTarget();//改变搜索按钮的颜色
                //handler.obtainMessage(3, etInfoText.getText().toString()).sendToTarget();//发送到搜索界面
                //通过bundle把数据携带过去
                /*Intent intent=new Intent(getApplicationContext(), MusicSearchActivity.class);
                Bundle bundle=new Bundle();
                bundle.putString("text",b);
                intent.putExtras(bundle);
                startActivity(intent);*/
                RxBus.getDefault().post(new MusicControlEvent(1001,b,"",""));
            }
        });

        //取历史记录
        if (SPM.getListStr("历史搜索", "historySearch", "") != null && SPM.getListStr("历史搜索", "historySearch", "").size() > 0) {
            stringHistoryData = new ArrayList<>();
            if (SPM.getListStr("历史搜索", "historySearch", "").size() > 6) {
                for (int i = 0; i < 6; i++) {
                    stringHistoryData.add(SPM.getListStr("历史搜索", "historySearch", "").get(i));
                }
            } else {
                for (String a : SPM.getListStr("历史搜索", "historySearch", "")) {
                    stringHistoryData.add(a);
                }
            }
        }

        if (!stringHistoryData.get(0).equals("")) {
            musicSearchAdapter = new MusicSearchAdapter(JxscApp.getContext(), R.layout.item_history_search, stringHistoryData);
            lvHistorySearch.setAdapter(musicSearchAdapter);
        }
    }
}
